<?php

declare(strict_types=1);

namespace app\admin\middleware;

use Closure;
use think\Config;
use think\Request;
use think\Response;

/**
 * Class AllowCrossDomain
 * @package app\admin\middleware
 */
class AllowCrossDomain
{

    protected $cookieDomain;
    /**
     * @param Config $config
     */
    public function __construct(Config $config)
    {
        $this->cookieDomain = $config->get('cookie.domain', '');
    }

    /**
     * 允许跨域请求
     * @access public
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle(Request $request, \Closure $next): Response
    {
        $response = $next($request);
        $origin = $request->header('Origin', '');

        //OPTIONS请求返回204请求
        if ($request->method(true) === 'OPTIONS') {
            $response->code(204);
        }
        $response->header([
            'Access-Control-Allow-Origin'      => $origin,
            'Access-Control-Allow-Methods'     => 'GET,POST,PUT',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Headers'     => '*',
        ]);

        return $response;
    }

}